package com.wanlian.service.impl;

import com.wanlian.common.*;
import com.wanlian.dao.*;
import com.wanlian.entity.*;
import com.wanlian.json.JsonStringUtil;
import com.wanlian.service.TaskTimerServices;
import com.wanlian.util.DateUtil;
import com.wanlian.util.HttpUtils;
import com.wanlian.util.Utils;
import com.wanlian.vo.ScorePersentAndPriceVo;
import com.wanlian.vo.ScoreVo;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class TaskTimerServicesImpl implements TaskTimerServices {


    @Autowired
    public UserDao userDao;

    @Autowired
    public DeviceDao deviceDao;

    @Autowired
    public DeviceConfigDao deviceConfigDao;

    @Autowired
    public UserScoreDao userScoreDao;

    @Autowired
    public ScoreHistoryDao scoreHistoryDao;

    @Autowired
    public WordBookDao wordBookDao;

    @Autowired
    public StorageDao storageDao;

    @Autowired
    public DeviceDataDao deviceDataDao;

    @Autowired
    public IntDetailDao intDetailDao;

    @Override
    public void doEdit() {
        List<String> onlines = wordBookDao.queryWbval1sByVal2("online_channel");
        ScorePersentAndPriceVo scorePersentAndPrice = this.calPersentAndPrice();
        List<User> users = userDao.queryAllEnableUser();
        List<Device> devices = deviceDao.queryEnableDevicesByChannels(onlines);

        Map<Integer, User> userMap = new HashMap<>();
        for (User user : users) {
            if (!userMap.containsKey(user.getId())) {
                userMap.put(user.getId(), user);
            }
        }
        for (Device device : devices) {
            if (userMap.containsKey(device.getUserid())) {
                User user = userMap.get(device.getUserid());
                Storage storage = storageDao.queryByDeviceId(device.getDeviceId());
                if (storage == null) {
                    continue;
                }
                //共享
                float save = storage.unitTransfer();
                double saved = TypeChange.floatToDoule(save);
                int shareSize = (int) Math.ceil(saved);
                if (shareSize < 16) {
                    scoreHistoryDao.deleteShareScore(device);
                    continue;
                } else {
                    DeviceData deviceData = deviceDataDao.queryByKey(device.getDevicekey());
                    float maxBw = 5;
                    float onlineLv = 0;
                    if (deviceData == null) {
                        continue;
                    }
                    if (deviceData != null) {
                        //最大带宽
                        maxBw = 5;// deviceData.getMaxBw();//deviceConfig.getMaxbandwidth();
                        //在线率
                        onlineLv = deviceData.getOnlineLv();
                    }
                    ScoreVo vo = calScoreVoOnline(shareSize, maxBw, onlineLv, scorePersentAndPrice.getIntRmb());
                    System.out.println("deviceId:" + device.getDeviceId() + "   username:" + user.getUsername() + vo.toString());
                    //添加积分记录
                    scoreHistoryDao.addOrUpdateShareScore(device, vo);
                }
            }
        }
    }


    private ScoreVo calScoreVo(int shareSize, float maxWidth, float online, float dxBL, float intBL, float int_rb) {
        float score = (float) (((Math.log(1 + shareSize) * 0.1 + Math.log(1 + maxWidth) * 0.7 + 1 * 0.2) * 21.195 * 0.013 * 24));
        //float sum_rmb = this.rounding(score);
        float xj_rmb = Utils.rounding((float) (score * dxBL));
        float token_rmb = Utils.rounding((float) (score * intBL));
        float dx_score = Utils.rounding(xj_rmb / 31 * online);
        float int_score = Utils.rounding((float) (token_rmb / 31 / int_rb * online));
        ScoreVo scoreVo = new ScoreVo();
        scoreVo.setDxScore(dx_score);
        scoreVo.setIntScore(int_score);
        return scoreVo;
    }


    public ScoreVo calScoreVoOnline(int shareSize, float maxWidth, float online, float int_rb) {
        float score = (float) (((Math.log(1 + shareSize) * 0.1 + Math.log(1 + maxWidth) * 0.8 + 1 * 0.2) * 21.195 * 0.013 * 24));
        //float sum_rmb = this.rounding(score);
        float token_rmb = Utils.rounding((float) (score * 1));
        System.out.println(token_rmb/31);
        float int_score = Utils.rounding((float) (token_rmb / 31 / int_rb * online));
        ScoreVo scoreVo = new ScoreVo();
        scoreVo.setIntScore(int_score);
        return scoreVo;
    }


    public static void main(String[] args) {
        System.out.println("磁盘：29g 带宽：5m");
        System.out.println(new TaskTimerServicesImpl().calScoreVoOnline(29, 5, 1, (float) 0.10));
        System.out.println("磁盘：1024g 带宽：5m");
        System.out.println(new TaskTimerServicesImpl().calScoreVoOnline(1024, 5, 1, (float) 0.10));
        System.out.println("磁盘：100 * 1024g 带宽：5m");
        System.out.println(new TaskTimerServicesImpl().calScoreVoOnline(100 * 1024, 5, 1, (float) 0.10));

    }


    private ScorePersentAndPriceVo calPersentAndPrice() {
        //积分四比六  电信4  int6
        WordBook int_wordBook = wordBookDao.queryWordBookByVal2("int_proportion");
        WordBook dx_wordBook = wordBookDao.queryWordBookByVal2("init_proportion");
        float intBL = Float.parseFloat(int_wordBook.getWbval1());
        float dxBL = Float.parseFloat(dx_wordBook.getWbval1());
        float int_rb = IntRmb.intRmb();
        ScorePersentAndPriceVo vo = new ScorePersentAndPriceVo();
        vo.setDxBL(dxBL);
        vo.setIntBL(intBL);
        vo.setIntRmb(int_rb);
        return vo;
    }


    @Override
    public void dointChange() {
        this.dointMainNetChange();
    }

    @Override
    public void dointStatuChange() {
        this.dointMainNetStatuChange();
    }

    @Override
    public void dointMainNetChange() {
        IntChangeDetail intChangeDetail = intDetailDao.queryOneDetail();
        if (intChangeDetail != null) {
            double intNum = intChangeDetail.getIntnum();
            String postUrl = String.format("%s/%s/%s/%f/%s", SystemStaticConfig.INT_TRANSFER_URL, SystemStaticConfig.INT_TRANSFER_FROM_ADDRESS,  intChangeDetail.getWallet(), intNum,  SystemStaticConfig.INT_TRANSFER_FROM_PASSWORD);
            System.out.println(postUrl);
            String data = HttpUtils.sendGetNoParam(postUrl);
            JSONObject jsonData = new JSONObject(data);
            String status = jsonData.get("status") + "";
            System.out.println(jsonData.toString());
            if (status.equals("success")) {
                String txHash   = jsonData.get("txHash") + "";
                intChangeDetail.setStatus(ConstantCode.STATUS_EXECUTING);
                intChangeDetail.setEthtx(txHash);
                intChangeDetail.setRequesttime(DateUtil.currentTimestamp());
                intDetailDao.update(intChangeDetail);
            }
        }
    }

    @Override
    public void dointMainNetStatuChange() {
        List<IntChangeDetail> list = intDetailDao.queryAllDetail(ConstantCode.STATUS_EXECUTING);
        for (IntChangeDetail intChangeDetail : list) {
            String url=String.format("%s/%s",SystemStaticConfig.INT_TRANSFER_GET_URL,intChangeDetail.getEthtx());
            String strs = HttpUtils.sendGetNoParam(url);
            JSONObject jsonData = new JSONObject(strs);
            System.out.println(jsonData.toString());
            String status = jsonData.get("status") + "";
            String data = jsonData.get("data") + "";
            JSONObject datastr = new JSONObject(data);
            if (status.equals("success")) {
                //成功
                intChangeDetail.setStatus(ConstantCode.STATUS_SUCCESS);
            } else {
                this.dotkjl(intChangeDetail);
            }
            intDetailDao.update(intChangeDetail);
        }
    }


    private void dotkjl(IntChangeDetail intChangeDetail) {
        //失败xx
        intChangeDetail.setStatus(ConstantCode.STATUS_FAIL);
        //失败退还积分
        ScoreHistory scoreHistory = scoreHistoryDao.queryById(intChangeDetail.getShid());
        UserScore userScore = userScoreDao.queryUserScoreByParams(scoreHistory.getUserId(), RankType.RANK_INT);
        userScore.setScore(userScore.getScore() + intChangeDetail.getIntnum());
        userScoreDao.update(userScore);
    }


}
